package com.ruoyi.business.utils;



import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.Locale;


import com.ruoyi.business.constant.IBusinessConstant;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;


/**
 * 包装freemarker,是根据模版产生目标文件的工具类
 * @author longsebo
 *
 */
@Slf4j
public class TemplateHelper {



	/**
	 * 封装freemarker,根据模版产生目标串
	 * @param paramMap
	 * @param templateString
	 * @param encoding 字符集
	 * @return 返回目标串
	 * @throws IOException
	 * @throws TemplateException
	 */
	public static  String createContentByString(Object paramMap, String templateString,String encoding) throws IOException, TemplateException{
		Template template = new Template(null, new StringReader(templateString), null);
		//执行插值，并输出到指定的输出流中
		OutputStreamWriter outputStreamWriter = null;
		BufferedWriter out = null;
		ByteArrayOutputStream byteOutputStream  = new ByteArrayOutputStream();

		try{
		outputStreamWriter = new OutputStreamWriter(
				byteOutputStream, encoding);
		out = new BufferedWriter(outputStreamWriter);
		template.setEncoding(IBusinessConstant.ENCODE_UTF_8);
		template.process(paramMap, out);
		return new String(byteOutputStream.toByteArray(),encoding);
		}finally{
			if(outputStreamWriter!=null){
				try {
					outputStreamWriter.close();
				} catch (IOException e) {
					log.error(e.getMessage(), e);
				}
			}
			if(out!=null){
				try {
					out.close();
				} catch (IOException e) {
					log.error(e.getMessage(), e);
				}
			}
		}
	}

}
